package com.example.utils;

import lombok.Data;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ImageCode {

    //二维码字符串
    private String codeStr ;
    //二维码宽度
    private final Integer IMAGE_WIDTH = 72;
    //二维码高度
    private final Integer IMAGE_HEIGHT = 32;
    //干扰线的数目
    private final Integer LINES = 15;
    //RGB随机数
    private final Integer RGB_NUM = 200;
    //验证码个数
    private final Integer CODE_NUM = 5 ;
    //随机数
    private static Random random = new Random();

    /**
     * 绘制验证么图片
     *
     * @return
     */
    public BufferedImage createImage() {
        BufferedImage bufferedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_3BYTE_BGR);
        //一、绘制背景
        Graphics2D graphics = bufferedImage.createGraphics();// 通过 graphics对象 绘制图片
        // 1.设置框内颜色
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
        //2、设置边框
        graphics.setColor(Color.RED);
        graphics.drawRect(0, 0, IMAGE_WIDTH - 1, IMAGE_HEIGHT - 1);
        //3.画干扰线
        for(int i=0 ; i<LINES ; i++){
            graphics.setColor(new Color(getRan(RGB_NUM),getRan(RGB_NUM), getRan(RGB_NUM))) ;
            graphics.drawLine(getRan(IMAGE_WIDTH), getRan(IMAGE_HEIGHT), getRan(IMAGE_WIDTH), getRan(IMAGE_HEIGHT)) ;
        }
        //4.生成的验证码字符串
        for (int i = 0; i < CODE_NUM; i++) {
            String rand = String.valueOf(random.nextInt(10));
            this.codeStr += rand;
            graphics.setFont(new Font("宋体",Font.PLAIN,20));
            graphics.setColor(new Color(getRan(RGB_NUM)+55, getRan(RGB_NUM)+55, getRan(RGB_NUM)+55));
            graphics.drawString(rand, IMAGE_WIDTH/6*i+4, IMAGE_HEIGHT/4*3);
        }
        return bufferedImage;
    }

    /**
     * 生成随机数
     * @return
     */
    private int getRan(int num){
        return random.nextInt(num);
    }

}
